package com.monas.client.view;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.UIJob;

import com.monas.client.AbstractMonasViewPart;
import com.monas.client.Activator;
import com.monas.client.Constants;
import com.monas.client.database.MonasResourceDatabase;
import com.monas.client.jfree.MonasTimeLineChart;
import com.monas.client.jfree.MonasTimeLineChartComposite;

public class MainView extends AbstractMonasViewPart {

	public static final String ID = "com.monas.client.view.MainView";

	private static final long DELAY = 10 * 1000;

	private static final String TIME = "Time";

	private static final String PERCENTAGE = "Percentage";

	private Composite itemComposite;

	private RefreshJob job;

	private LinkedList<MonasTimeLineChartComposite> charts = new LinkedList<MonasTimeLineChartComposite>();

	@Override
	public void createPartControl(Composite parent) {
		// create scroll form and header
		createForm(parent, "DASHBOARD");

		// create dashboard item
		createDashboard();
	}

	private void createDashboard() {

		itemComposite = new Composite(form.getBody(), SWT.None);
		GridLayout newLayout = new GridLayout(2, true);
		itemComposite.setLayout(newLayout);
		itemComposite
				.setBackground(new Color(form.getDisplay(), 255, 255, 255));

		// addRandomTimelineChart();
		addTimelineCharts();

		// buat schedule untuk refresh dashboard
		job = new RefreshJob();
		job.setSystem(true);
		job.setPriority(RefreshJob.DECORATE);
		job.schedule(DELAY);
	}

	@Override
	public void refresh() {
		refreshCharts();
		itemComposite.layout();

		// Melakukan refresh ke semua view selain MainView.
		IWorkbenchPage activePage = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage();
		for (IViewReference view : activePage.getViewReferences()) {
			if (!ID.equals(view.getId())) {
				AbstractMonasViewPart viewPart = (AbstractMonasViewPart) activePage
						.findView(view.getId());
				viewPart.refresh();
			}
		}
	}

	public void addTimelineCharts() {
		try {
			MonasResourceDatabase database = MonasResourceDatabase
					.getInstance();

			charts.add(addTimelineChart("CPU Used", database.getDashboardCPU()));
			charts.add(addTimelineChart("Memory Used",
					database.getDashboardMemory()));
			charts.add(addTimelineChart("Harddisk Used",
					database.getDashboardHdd()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void refreshCharts() {
		try {
			MonasResourceDatabase database = MonasResourceDatabase
					.getInstance();

			MonasTimeLineChartComposite cpu = charts.get(0);
			cpu.getChart().clearData();
			addContentChart(database.getDashboardCPU(), cpu.getChart());

			MonasTimeLineChartComposite memory = charts.get(1);
			memory.getChart().clearData();
			addContentChart(database.getDashboardMemory(), memory.getChart());

			MonasTimeLineChartComposite disk = charts.get(2);
			disk.getChart().clearData();
			addContentChart(database.getDashboardHdd(), disk.getChart());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public MonasTimeLineChartComposite addTimelineChart(String title,
			List<Object[]> results) {

		MonasTimeLineChartComposite chartComposite = new MonasTimeLineChartComposite(
				itemComposite, title, TIME, PERCENTAGE);
		MonasTimeLineChart chart = chartComposite.createChart();

		addContentChart(results, chart);
		chart.createChart();

		chartComposite.createComposite(chart);

		return chartComposite;
	}

	private void addContentChart(List<Object[]> results,
			MonasTimeLineChart chart) {
		String label = null;
		LinkedList<Timestamp> times = new LinkedList<Timestamp>();
		LinkedList<Number> values = new LinkedList<Number>();

		int start = 0;
		for (int i = start; i < results.size(); i++) {
			Object[] fields = results.get(i);
			if (i == start) {
				label = (String) fields[0];
			} else if (i % 10 == 0) {
				chart.addTimeSeries(label, times, values);
				label = (String) fields[0];
				times = new LinkedList<Timestamp>();
				values = new LinkedList<Number>();
			}

			Timestamp time = (Timestamp) fields[1];
			Number number = (Number) fields[2];

			times.add(time);
			values.add(number);
		}

		chart.addTimeSeries(label, times, values);
	}

	@Override
	public void dispose() {
		toolkit.dispose();
		super.dispose();
	}

	/**
	 * Job untuk refresh data terakhir.
	 * 
	 * @author eko wahyudi
	 * 
	 */
	private class RefreshJob extends UIJob {

		/**
		 * Default kontruktor.
		 */
		public RefreshJob() {
			super("Refresh Job for Last Data");
		}

		@Override
		public IStatus runInUIThread(IProgressMonitor monitor) {
			monitor.beginTask("Refreshing last data", IProgressMonitor.UNKNOWN);
			refresh();
			job.schedule(DELAY);
			return Status.OK_STATUS;
		}

	}

	@Override
	public Image getViewImage() {
		return Activator.getImage(Constants.IMAGE_DASHBOARD);
	}

}
